using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ReportViewer.ReportsWS;
using System.Web.Services.Protocols;
using System.Configuration;



namespace ReportViewer
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ReportParameters : Form
    {
        #region Properties

        private ReportParameter[] parametersField;
        /// <summary>
        /// Pass in the Parameters to be displayed
        /// </summary>
        public ReportParameter[] Parameters
        {
            get { return parametersField; }
            set { parametersField = value; }
        }

        private ReportViewer reportViewerField;
        /// <summary>
        /// Make available the Report Viewer to any calling methods
        /// </summary>
        public ReportViewer ReportViewer
        {
            get { return reportViewerField; }
            set { reportViewerField = value; }
        }

        /// <summary>
        /// Set the title of the Parameter
        /// </summary>
        public String Title
        {
            set { Text = value; }
        }

        /// <summary>
        /// Set the Description of the Parameter
        /// </summary>
        public String Description
        {
            set { lblDescription.Text = value; }
        }

        private Uri reportURLField;
        /// <summary>
        /// The URL required for the report
        /// </summary>
        public Uri ReportURL
        {
            get { return reportURLField; }
            set { reportURLField = value; }
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        public ReportParameters()
        {
            InitializeComponent();
        }

        #region Form Controls

        private void btnOK_Click(object sender, EventArgs e)
        {

            if (Parameters.Length != 0)
            {
                Microsoft.Reporting.WinForms.ReportParameter[] param = new Microsoft.Reporting.WinForms.ReportParameter[Parameters.Length];
                Int32 paramCount = 0;

                foreach (ReportParameter rp in Parameters)
                {
                    switch (rp.Type)
                    {
                        case ParameterTypeEnum.Boolean:
                            throw new Exception("Not yet developed");
                        case ParameterTypeEnum.DateTime:
                            throw new Exception("Not yet developed");
                        case ParameterTypeEnum.Float:
                            throw new Exception("Not yet developed");
                        case ParameterTypeEnum.Integer:
                            FindControlValue(param, paramCount, rp);
                            break;
                        case ParameterTypeEnum.String:
                            FindControlValue(param, paramCount, rp);
                            break;
                        default:
                            throw new ApplicationException("Unknown Report Parameter type");
                    }

                    paramCount = paramCount + 1;
                }

                ReportViewer.Report.ServerReport.SetParameters(param);

                foreach (Microsoft.Reporting.WinForms.ReportParameter p in param)
                {
                    ReportURL = new Uri(String.Format("{0}&{1}={2}", ReportURL, p.Name, p.Values[0]));
                }
            }

            ReportViewer.Show();

            ReportViewerWeb reportViewerWeb = new ReportViewerWeb();
            if (ReportURL != null && ConfigurationManager.AppSettings["ReportConfiguration"] != null)
            {
                ReportURL = new Uri(String.Format("{0}{1}", ReportURL, ConfigurationManager.AppSettings["ReportConfiguration"]));
            }

            reportViewerWeb.WebBrowser.Url = ReportURL;
            reportViewerWeb.Show();

            Close();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region Private Methods


        private void ReportParameters_Load(object sender, EventArgs e)
        {
            if (Parameters != null)
            {
                int x = 50;
                int y = 0;
                try
                {
                    SuspendLayout();
                    panel1.SuspendLayout();
                    panel1.SendToBack();

                    foreach (ReportParameter rp in Parameters)
                    {
                        switch (rp.Type)
                        {
                            case ParameterTypeEnum.Boolean:
                                throw new Exception("Not yet developed");
                            case ParameterTypeEnum.DateTime:
                                throw new Exception("Not yet developed");
                            case ParameterTypeEnum.Float:
                                throw new Exception("Not yet developed");
                            case ParameterTypeEnum.Integer:
                                y = DisplayUserControl(x, y, rp);
                                break;
                            case ParameterTypeEnum.String:
                                y = DisplayUserControl(x, y, rp);
                                break;
                            default:
                                throw new ApplicationException("Unknown Report Parameter type");
                        }
                    }

                    //Position and resize the screen depending onthe number of parameters
                    panel1.Height = y + 60;
                    Height = y + 140;
                    btnOk.Top = y + 20;
                    btnCancel.Top = y + 20;

                    panel1.ResumeLayout(false);
                    ResumeLayout(false);
                }
                catch (SoapException ex)
                {
                    MessageBox.Show(ex.Detail.InnerXml);
                }

            }
        }

        /// <summary>
        /// Return the avalaile values
        /// </summary>
        /// <param name="validValues">Pass in the RDL files valid parameters</param>
        /// <returns>a Key Value Pair of the results</returns>
        private static List<KeyValuePair<String, Int32?>> GetAvailableValues(IEnumerable<ValidValue> validValues)
        {

            List<KeyValuePair<String, Int32?>> listItems = new List<KeyValuePair<String, Int32?>>();
            foreach (ValidValue validValue in validValues)
            {
                listItems.Add(new KeyValuePair<String, Int32?>(validValue.Label, Convert.ToInt32(validValue.Value)));
            }

            return listItems;

        }

        private void FindControlValue(Microsoft.Reporting.WinForms.ReportParameter[] param, Int32 paramCount, ReportParameter rp)
        {

            switch (rp.Type)
            {
                case ParameterTypeEnum.Boolean:
                    //param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, Convert.ToBoolean(cb.Text).ToString());
                    break;
                case ParameterTypeEnum.DateTime:
                    //param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, Convert.ToDateTime(cb.Text).ToString());
                    break;
                case ParameterTypeEnum.Float:
                    //param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, Convert.ToDouble(cb.Text).ToString());
                    break;
                case ParameterTypeEnum.Integer:
                    //if (cb.Text.Length == 0)
                    //{
                    //    cb.Text = "0";
                    //}
                    //param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, Convert.ToInt32(cb.Text).ToString());
                    break;
                case ParameterTypeEnum.String:
                    if (rp.ValidValues != null)
                    {
                        ComboBox comboBox = (ComboBox)FindControl(rp.Name);
                        if (comboBox != null)
                        {
                            param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, comboBox.SelectedValue.ToString());
                        }

                        else
                        {
                            throw new ApplicationException(String.Format("Unable to find Control - {0}", rp.Name));
                        }
                    }
                    else
                    {
                        TextBox t = (TextBox)FindControl(rp.Name);
                        if (t != null)
                        {
                            param[paramCount] = new Microsoft.Reporting.WinForms.ReportParameter(rp.Name, t.Text);
                        }

                        else
                        {
                            throw new ApplicationException(String.Format("Unable to find Control - {0}", rp.Name));
                        }
                    }
                    break;
                default:
                    throw new ApplicationException("Unknown Report Parameter type");
            }


        }

        private Control FindControl(string strControlName)
        {
            if (strControlName.Length == 0 || Controls.Find(strControlName, true).Length == 0)
                return null;

            return Controls.Find(strControlName, true)[0];
        }

        private int DisplayUserControl(int x, int y, ReportParameter rp)
        {
            
                //Lets see if we have a number of values, if we have then display a ComboBox
                if (rp.ValidValues != null)
                {
                    List<KeyValuePair<String, Int32?>> list = GetAvailableValues(rp.ValidValues);
                    ParameterControls.Pulldown paramPullDown = new ParameterControls.Pulldown(rp.Prompt, rp.Name);
                    paramPullDown.BindData(list);
                    paramPullDown.Location = new Point(x, y);
                    //If the Parameter is Hidden, if it is then we should not display anything, but it will be hidden        
                    if (rp.Prompt == "")
                        paramPullDown.Visible = false;
                    else
                        y = y + 50;

                    panel1.Controls.Add(paramPullDown);
                    
                }
                else
                {
                    ParameterControls.Text paramText = new ParameterControls.Text(rp.Prompt, rp.Name);
                    paramText.Location = new Point(x, y);
                    if (rp.DefaultValues != null)
                    {
                        if (rp.DefaultValues.Length != 0)
                        {
                            paramText.DefaultValue = rp.DefaultValues[0];
                        }
                    }

                    //If the Parameter is Hidden, if it is then we should not display anything, but it will be hidden
                    if (rp.Prompt == "")
                        paramText.Visible = false;
                    else
                        y = y + 50;

                    panel1.Controls.Add(paramText);
                    
                }
            
            return y;

        }

        #endregion


    }

    #region ComboItem

    /// <summary>
    /// 
    /// </summary>
    public class ComboItem
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disp"></param>
        /// <param name="myvalue"></param>
        public ComboItem(string disp, string myvalue)
        {
            if (disp != null)
                display = disp;
            else
                display = "";
            if (myvalue != null)
                val = myvalue;
            else
                val = "";
        }

        private string val;
        /// <summary>
        /// 
        /// </summary>
        public string Value
        {
            get { return val; }
            set { val = value; }
        }

        private string display;
        /// <summary>
        /// 
        /// </summary>
        public string Display
        {
            get { return display; }
            set { display = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return display;
        }
    }
    #endregion
}